import uuid
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser
from django.core.paginator import Paginator
from django.utils import timezone
from django.db.models import Q
from .lib.Neo4jServices import *

from .serializers import GraphSerializer
from drf_spectacular.utils import extend_schema, OpenApiExample,OpenApiParameter, OpenApiResponse
from drf_spectacular.types import OpenApiTypes
from rest_framework.decorators import action
from rest_framework.views import APIView
from django.http import JsonResponse

@extend_schema(tags = ["Neo4j专利图谱"])
class GraphNeo4jPatentView(viewsets.ModelViewSet):#APIView):
    """图谱API"""
    permission_classes = [AllowAny]
    @extend_schema(
        operation_id = "获取专利图谱",
        summary = "获取特定专利的图谱",
        # 执行序列化器
        responses={200: Response()},
        parameters = [
            OpenApiParameter(name = "internal_id_elasticsearch",description = "专利/论文的ID",type = OpenApiTypes.STR,required = True,
                examples=[OpenApiExample('例子',summary='ID',description='专利的ID',value="97883805"),]),
            OpenApiParameter(name = "patent_name",description = "专利名称",type = OpenApiTypes.STR,required = False),
            OpenApiParameter(name = "neo4j_label",description = "图谱节点类型",type = OpenApiTypes.STR,required = False),
        ]
    )
    @action(detail=False, methods=['get'])
    def retreive(self, request):
        internal_id_elasticsearch = request.GET.get('internal_id_elasticsearch')
        patent_name = request.GET.get('patent_name')
        neo4j_label = request.GET.get('neo4j_label')
    
        # 确保至少一个查询参数被提供
        if not (internal_id_elasticsearch or patent_name or neo4j_label):
            return JsonResponse({"error": "必须提供至少一个查询参数"}, status=400)
    
        # 连接到您的 Neo4j 数据库
        NEO4J_CONFIG = {
            "uri":"neo4j://81.70.135.187:37687",
            "user":"neo4j",
            "password":"vPn**12@@56"
        }

        service = Neo4jServices(**NEO4J_CONFIG)
    
        try:
            # 调用服务获取 patent graph 数据
            result = service.get_patent_graph(
                internal_id_elasticsearch=internal_id_elasticsearch,
                patent_name=patent_name,
                neo4j_label=neo4j_label
            )
    
            # 序列化查询结果
            serialized_data = []
            for item in result:
                serialized_record = {
                    "patent": item["patent"],
                    "relationship": item["relationship"],
                    "related_node": item["related_node"]
                }
                serialized_data.append(serialized_record)
    
            return JsonResponse({"data": serialized_data}, safe=False)
    
        except Exception as e:
            import traceback
            traceback.print_exc()
            logger.error("Exception {} when request for {}".format(e,internal_id_elasticsearch))
            # 捕捉并返回错误信息
            return JsonResponse({"error": str(e)}, status=500)
    
        finally:
            # 确保关闭数据库服务
            service.close()
